package com.c2b.algorithm.leetcode.jzoffer;

/**
 * @author c2b
 * @since 2023/3/8 16:42
 */
public class JzOffer0073ReverseSentence_ {

    public String ReverseSentence(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        // 先整体反转一次字符串
        int length = str.length();
        char[] chars = str.toCharArray();
        reverse(chars, 0, length - 1);
        for (int i = 0; i < length; i++) {
            int j = i;
            while (j < length && chars[j] != ' ') {
                j++;
            }
            // 反转两个' '中间的单词
            reverse(chars, i, j - 1);
            i = j;
        }
        return new String(chars);
    }

    private void reverse(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }


    public static void main(String[] args) {
        JzOffer0073ReverseSentence_ jzOffer0073ReverseSentence = new JzOffer0073ReverseSentence_();
        String s = jzOffer0073ReverseSentence.ReverseSentence("nowcoder. a am I");
        System.out.println(s);
    }
}
